package link.impl;

import link.LinkList;


/**
 * @author niann
 * @description 单向链表
 * @since 2024/8/26 下午9:44
 **/
public class LinkListImpl<E> implements LinkList<E> {

    private int size;

    private final Node<E> head = new Node<>();

    @Override
    public int Size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }


    /**
     * test list: [1,2,3,4,5,6,7,8] index: 3 e: 9
     * @param index
     * @param e
     */
    @Override
    public void insert(int index, E e) {
        if (index==size){
            insert(e);
            return;
        }
        if (index>size||index<0){
            throw new RuntimeException("索引越界");
        }
        var current= head;
        var next = current.next;
        var node2 = new Node<E>();
        node2.data=e;
        for (int i = 0; i < index; i++) {
            current=next;
            next=next.next;
        }
        node2.next=next;
        current.next=node2;
        size++;
    }


    @Override
    public void insert(E e) {
        Node<E> node = head;
        while (node.next!=null){
            node=node.next;
        }
        Node<E> node2 = new Node<>();
        node2.data=e;
        node.next=node2;
        size++;
    }

    @Override
    public void delete(int index) {
        if (index>=size||index<0){
            throw new RuntimeException("索引越界");
        }
        var node = head;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        node.next=node.next.next;
    }

    @Override
    public E get(int index) {
        if (index>=size||index<0){
            throw new RuntimeException("索引越界");
        }
        var node = head.next;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node.data;
    }

    @Override
    public int find(E e) {
        for (int i = 0; i < size; i++) {
            if (get(i).equals(e)){
                return i;
            }
        }
        return -1;
    }

    @Override
    public void clear() {
        head.next=null;
        size=0;
    }

    @Override
    public String toString() {
        StringBuilder s = new StringBuilder();
        s.append("[");
        while (head.next!=null){
            s.append(head.next.data).append(",");
            head.next=head.next.next;
        }
        if (size!=0){
            s.delete(s.length()-1,s.length());
        }
        s.append("]");
        return s.toString();
    }
    class Node<E>{
        E data;
        Node<E> next;
    }
}

